package com.yijumao.shop.controller;

import com.yijumao.shop.domain.Cart;
import com.yijumao.shop.domain.CartItem;
import com.yijumao.shop.domain.Item;
import com.yijumao.shop.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * @author konley
 * @date 2020-11-15 14:58
 */
@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private ItemService itemService;

    //清空购物车功能
    @RequestMapping("/clear")
    public String clear(HttpSession session){
        Cart cart = (Cart) session.getAttribute("cart");
        cart.clear();
        session.removeAttribute("cart");
        return "cart";
    }

    //删除购物车的功能
    @RequestMapping("/delete")
    public String delete(int id,HttpSession session){
        Cart cart = (Cart) session.getAttribute("cart");
        cart.delete(id);
        //如果购物车中没有元素了，销毁session
        if(cart.getCartItems().isEmpty()){
            session.removeAttribute("cart");
        }
        return "cart";
    }

    //添加购物车的功能
    @RequestMapping("/add")
    public String add(int count, int id, HttpSession session){
        //根据id查商品信息
        Item item = itemService.selectByPrimaryKey(id);
        //创建购物项
        CartItem cartItem = new CartItem(item, count);
        //判断是否有购物车
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart==null){
            //没有购物车 创建之
            cart = new Cart();
            //添加购物项
            cart.addCartItem(cartItem);
            //添加到session
            session.setAttribute("cart",cart);
        }else{
            //添加购物项
            cart.addCartItem(cartItem);
        }
        return "cart";
    }
}
